package com.peng.leetcode.tree;

import java.util.ArrayDeque;

/**
 * MinDepthByQueue
 * <p>
 * Created on 2022/11/29
 *
 * @author lupeng
 */
public class MinDepthByQueue {

    public static void main(String[] args) {
        TreeNode t = TreeMain.array2tree(new Integer[]{3, 9, 20, null, null, 15, 7});
        System.out.println(new MinDepthByQueue().minDepth(t));
    }

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int ans = Integer.MAX_VALUE;
        ArrayDeque<TreeNode> q = new ArrayDeque<>();
        while (root != null || !q.isEmpty()) {
            while (root != null) {
                q.offer(root);
                root = root.left;
            }
            TreeNode n = q.pollLast();
            if (n.left == null && n.right == null) {
                ans = Math.min(ans, q.size() + 1);
            }
            root = n.right;
        }
        return ans;
    }

}
